// 全局配置：后端基地址
const BASE_URL = 'http://127.0.0.1:5000';

// 复用的状态
let netSelectedFiles = []; // { name, blob }
let netFileList = []; // 来自后端的可选文件名数组

window.addEventListener('DOMContentLoaded', () => {
  initNetworkPicker();
  initUploadFlow();
  initCharts();
});

function initNetworkPicker() {
  const fetchBtn = document.getElementById('fetch-list-btn');
  const clearBtn = document.getElementById('clear-selection-btn');
  const countEl = document.getElementById('net-selected-count');

  const pickerModalEl = document.getElementById('pickerModal');
  const pickerListEl = document.getElementById('picker-list');
  const pickerConfirmBtn = document.getElementById('picker-confirm-btn');

  // 内嵌备选元素
  const pickerInlineEl = document.getElementById('picker-inline');
  const pickerInlineListEl = document.getElementById('picker-inline-list');
  const pickerInlineConfirmBtn = document.getElementById('picker-inline-confirm-btn');
  const pickerInlineCancelBtn = document.getElementById('picker-inline-cancel-btn');

  let pickerModal = null;
  try {
    // Bootstrap 可能不存在，try/catch避免报错
    // eslint-disable-next-line no-undef
    pickerModal = pickerModalEl ? new bootstrap.Modal(pickerModalEl) : null;
  } catch (e) {
    pickerModal = null;
  }

  function updateCount() {
    countEl.textContent = `已选择${netSelectedFiles.length}个文件`;
  }

  clearBtn?.addEventListener('click', () => {
    netSelectedFiles = [];
    updateCount();
    // 同时隐藏内嵌选择器
    if (pickerInlineEl) pickerInlineEl.style.display = 'none';
  });

  // 显示选择器：优先模态，失败则显示内嵌
  function showPickerWithFallback() {
    let fallbackDone = false;
    const fallback = () => {
      if (fallbackDone) return;
      fallbackDone = true;
      if (pickerInlineEl) pickerInlineEl.style.display = 'block';
    };
    if (pickerModal) {
      try {
        pickerModal.show();
      } catch (e) {
        fallback();
        return;
      }
      setTimeout(() => {
        const visible = pickerModalEl && pickerModalEl.classList.contains('show');
        const display = pickerModalEl ? getComputedStyle(pickerModalEl).display : 'none';
        if (!visible || display === 'none') fallback();
      }, 200);
    } else {
      fallback();
    }
  }

  fetchBtn?.addEventListener('click', async () => {
    // 拉取列表
    if (pickerListEl) pickerListEl.innerHTML = '<div class="text-muted">加载中...</div>';
    if (pickerInlineListEl) pickerInlineListEl.innerHTML = '<div class="text-muted">加载中...</div>';

    const list = await getCsvList();
    netFileList = list || [];

    // 渲染项（同时准备给模态和内嵌）
    const renderItems = (container) => {
      if (!container) return;
      if (!netFileList.length) {
        container.innerHTML = '<div class="text-danger">未找到CSV文件，请检查后端data目录。</div>';
        return;
      }
      container.innerHTML = '';
      netFileList.forEach((fname, idx) => {
        const item = document.createElement('div');
        item.className = 'list-group-item d-flex justify-content-between align-items-center';
        item.innerHTML = `
          <div class="form-check">
            <input class="form-check-input" type="checkbox" id="pick-${idx}">
            <label class="form-check-label" for="pick-${idx}">${fname}</label>
          </div>
          <span class="badge bg-primary rounded-pill">CSV</span>
        `;
        container.appendChild(item);
      });
    };

    renderItems(pickerListEl);
    renderItems(pickerInlineListEl);

    // 显示模态或回退到内嵌选择器
    showPickerWithFallback();
  });

  // 确认选择（模态）
  pickerConfirmBtn?.addEventListener('click', async () => {
    await collectSelectedFromContainer(pickerListEl);
    updateCount();
    try { pickerModal?.hide?.(); } catch (e) {}
  });

  // 内嵌确认/取消
  pickerInlineConfirmBtn?.addEventListener('click', async () => {
    await collectSelectedFromContainer(pickerInlineListEl);
    updateCount();
    pickerInlineEl && (pickerInlineEl.style.display = 'none');
  });
  pickerInlineCancelBtn?.addEventListener('click', () => {
    pickerInlineEl && (pickerInlineEl.style.display = 'none');
  });
}

async function collectSelectedFromContainer(container) {
  if (!container) return;
  const checked = Array.from(container.querySelectorAll('input.form-check-input:checked'));
  if (checked.length > 3) {
    alert('最多选择3个CSV文件');
    return;
  }
  const names = checked.map((inp) => inp.nextElementSibling?.textContent || '');
  const downloads = await Promise.all(names.map((n) => downloadCsv(n)));
  netSelectedFiles = downloads.filter(Boolean);
}

async function getCsvList() {
  try {
    const res = await fetch(`${BASE_URL}/list-files`, { method: 'GET' });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    return Array.isArray(data?.files) ? data.files : [];
  } catch (e) {
    console.error('获取CSV列表失败', e);
    return [];
  }
}

async function downloadCsv(filename) {
  try {
    const res = await fetch(`${BASE_URL}/download-file?name=${encodeURIComponent(filename)}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const blob = await res.blob();
    return { name: filename, blob };
  } catch (e) {
    console.error('下载失败', filename, e);
    return null;
  }
}

function initUploadFlow() {
  const uploadBtn = document.getElementById('upload-btn');
  const successEl = document.getElementById('upload-success');

  uploadBtn?.addEventListener('click', async () => {
    successEl.style.display = 'none';

    const form = new FormData();
    if (netSelectedFiles.length) {
      // 与后端字段匹配：activity/glucose/clhls
      const findByPartial = (key) => netSelectedFiles.find(f => (f.name || '').toLowerCase().includes(key));
      const activity = findByPartial('activity');
      const glucose = findByPartial('glucose');
      const clhls = findByPartial('clhls');
      if (!activity || !glucose || !clhls) {
        alert('请确保选择 activity.csv、glucose.csv、clhls.csv');
        return;
      }
      form.append('activity', activity.blob, activity.name);
      form.append('glucose', glucose.blob, glucose.name);
      form.append('clhls', clhls.blob, clhls.name);
    } else {
      // 回退：使用隐藏的本地输入（兼容旧逻辑）
      const af = document.getElementById('activity-file');
      const gf = document.getElementById('glucose-file');
      const cf = document.getElementById('clhls-file');
      if (!af?.files?.[0] || !gf?.files?.[0] || !cf?.files?.[0]) {
        alert('请上传所有三个CSV文件（或先通过“网络选择”完成选择）');
        return;
      }
      form.append('activity', af.files[0], af.files[0].name);
      form.append('glucose', gf.files[0], gf.files[0].name);
      form.append('clhls', cf.files[0], cf.files[0].name);
    }

    try {
      const res = await fetch(`${BASE_URL}/upload`, { method: 'POST', body: form });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      successEl.style.display = 'block';
      await refreshChartsData();
    } catch (e) {
      console.error('上传失败', e);
      alert('上传失败，请检查后端服务');
    }
  });
}

function initCharts() {
  // 初始化占位（实际数据由刷新流程加载）
  const gc = document.getElementById('glucose-chart');
  if (gc) {
    Plotly.newPlot(gc, [{ y: [0], type: 'scatter' }], { margin: { t: 20 } });
  }
  const ah = document.getElementById('activity-heatmap');
  if (ah) {
    ah.textContent = '活动热力图将在上传后显示';
  }
  const hr = document.getElementById('health-radar');
  if (hr) {
    hr.textContent = '雷达图将在上传后显示';
  }
}

async function refreshChartsData() {
  try {
    const res = await fetch(`${BASE_URL}/data`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    // 数据是DailyRecord列表
    renderGlucoseChart(data);
    renderActivityHeatmap(data);
    renderHealthRadar(data);
    // 调用预警接口：选择最后一条记录的person_id
    const last = Array.isArray(data) && data.length ? data[data.length - 1] : null;
    if (last && last.person_id) {
      await checkAlert(last.person_id);
    }
  } catch (e) {
    console.error('刷新图表数据失败', e);
  }
}

function renderGlucoseChart(list) {
  const gc = document.getElementById('glucose-chart');
  if (!gc) return;
  const y = Array.isArray(list) ? list.map((d) => d.glucose_mean ?? d.value ?? d) : [];
  const x = Array.isArray(list) ? list.map((d) => d.date ?? '') : [];
  Plotly.newPlot(gc, [{ x, y, type: 'scatter', mode: 'lines+markers', line: { color: '#165DFF' } }], { margin: { t: 20 } });
}

function renderActivityHeatmap(list) {
  const container = document.getElementById('activity-heatmap');
  if (!container) return;
  // 构造矩阵：日期 × 指标
  const dates = list.map(d => d.date);
  const metrics = ['activity_score','sleep_quality','exercise_freq','diet_score','adl'];
  const values = metrics.map(key => list.map(d => Number(d[key] ?? 0)));
  const data = [];
  // 转换为 [xIndex, yIndex, value]
  for (let i = 0; i < dates.length; i++) {
    for (let j = 0; j < metrics.length; j++) {
      data.push([i, j, values[j][i]]);
    }
  }
  const maxVal = Math.max(1, ...data.map(v => v[2]));
  const chart = echarts.init(container);
  chart.setOption({
    title: { text: '行为热力图', left: 'center' },
    tooltip: { position: 'top' },
    grid: { height: '60%', top: '10%' },
    xAxis: { type: 'category', data: dates, axisLabel: { rotate: 45 } },
    yAxis: { type: 'category', data: ['活动','睡眠','运动','饮食','ADL'] },
    visualMap: { min: 0, max: maxVal, orient: 'horizontal', left: 'center', bottom: 0 },
    series: [{
      name: '行为热力图', type: 'heatmap', data,
      emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.5)' } }
    }]
  });
}

function renderHealthRadar(list) {
  const container = document.getElementById('health-radar');
  if (!container) return;
  const latest = Array.isArray(list) && list.length ? list[list.length - 1] : null;
  if (!latest) { container.textContent = '暂无数据'; return; }
  const indicators = [
    { name: '活动评分', max: 100 },
    { name: '睡眠质量', max: 1 },
    { name: '运动频率', max: 1 },
    { name: '饮食评分', max: 1 },
    { name: '日常生活能力', max: 1 }
  ];
  const values = [
    Number(latest.activity_score ?? 0),
    Number(latest.sleep_quality ?? 0),
    Number(latest.exercise_freq ?? 0),
    Number(latest.diet_score ?? 0),
    Number(latest.adl ?? 0)
  ];
  const chart = echarts.init(container);
  chart.setOption({
    title: { text: '健康评分雷达图', left: 'center' },
    radar: { indicator: indicators },
    series: [{ type: 'radar', data: [{ value: values, name: '当前评分', areaStyle: { color: 'rgba(22,93,255,0.3)' }, lineStyle: { color: '#165DFF' } }] }]
  });
}

// 手机内覆盖层弹窗：选择器和预警
const pickerOverlayEl = document.getElementById('picker-overlay');
const pickerOverlayListEl = document.getElementById('picker-overlay-list');
const pickerOverlayConfirmBtn = document.getElementById('picker-overlay-confirm-btn');
const pickerOverlayCancelBtn = document.getElementById('picker-overlay-cancel-btn');
const pickerOverlayCloseBtn = document.getElementById('picker-overlay-close');
const alertOverlayEl = document.getElementById('alert-overlay');
const alertOverlayConfirmBtn = document.getElementById('alert-overlay-confirm-btn');

function showPickerOverlay(items) {
  if (!pickerOverlayEl) return false;
  pickerOverlayListEl.innerHTML = '';
  items.forEach(name => {
    const id = `overlay-item-${name}`;
    const div = document.createElement('div');
    div.className = 'list-group-item d-flex justify-content-between align-items-center';
    div.innerHTML = `
      <span>${name}</span>
      <input type="checkbox" class="form-check-input" id="${id}" data-name="${name}">
    `;
    pickerOverlayListEl.appendChild(div);
  });
  pickerOverlayEl.style.display = 'block';
  return true;
}
function hidePickerOverlay() {
  if (pickerOverlayEl) pickerOverlayEl.style.display = 'none';
}
function showAlertOverlay() {
  if (alertOverlayEl) alertOverlayEl.style.display = 'block';
}
function hideAlertOverlay() {
  if (alertOverlayEl) alertOverlayEl.style.display = 'none';
}

// 绑定覆盖层按钮事件
if (pickerOverlayCancelBtn) pickerOverlayCancelBtn.addEventListener('click', hidePickerOverlay);
if (pickerOverlayCloseBtn) pickerOverlayCloseBtn.addEventListener('click', hidePickerOverlay);
if (alertOverlayConfirmBtn) alertOverlayConfirmBtn.addEventListener('click', hideAlertOverlay);

// 网络文件选择器逻辑（优先使用手机内覆盖层）
(function initNetworkPicker() {
  const fetchBtn = document.getElementById('fetch-list-btn');
  const clearBtn = document.getElementById('clear-selection-btn');
  const netSelectedCountEl = document.getElementById('net-selected-count');

  const inlinePicker = document.getElementById('picker-inline');
  const inlineListEl = document.getElementById('picker-inline-list');
  const inlineConfirmBtn = document.getElementById('picker-inline-confirm-btn');
  const inlineCancelBtn = document.getElementById('picker-inline-cancel-btn');

  function renderInlineList(items) {
    inlineListEl.innerHTML = '';
    items.forEach(name => {
      const id = `inline-item-${name}`;
      const div = document.createElement('div');
      div.className = 'list-group-item d-flex justify-content-between align-items-center';
      div.innerHTML = `
        <span>${name}</span>
        <input type="checkbox" class="form-check-input" id="${id}" data-name="${name}">
      `;
      inlineListEl.appendChild(div);
    });
  }

  // 用于存储用户选择
  let selectedNames = [];

  function updateSelectedCount() {
    netSelectedCountEl.textContent = `已选择${selectedNames.length}个文件`;
  }

  function collectChecked(containerEl) {
    const checks = containerEl.querySelectorAll('input[type="checkbox"]');
    const names = [];
    checks.forEach(ch => { if (ch.checked) names.push(ch.getAttribute('data-name')); });
    return names;
  }

  // 确认选择（覆盖层）
  if (pickerOverlayConfirmBtn) {
    pickerOverlayConfirmBtn.addEventListener('click', () => {
      const names = collectChecked(pickerOverlayEl);
      if (names.length === 0 || names.length > 3) {
        alert('请至少选择1个且不超过3个文件');
        return;
      }
      selectedNames = names;
      updateSelectedCount();
      hidePickerOverlay();
    });
  }

  // 确认选择（内嵌）
  if (inlineConfirmBtn) {
    inlineConfirmBtn.addEventListener('click', () => {
      const names = collectChecked(inlinePicker);
      if (names.length === 0 || names.length > 3) {
        alert('请至少选择1个且不超过3个文件');
        return;
      }
      selectedNames = names;
      updateSelectedCount();
      inlinePicker.style.display = 'none';
    });
  }
  if (inlineCancelBtn) inlineCancelBtn.addEventListener('click', () => inlinePicker.style.display = 'none');

  // 清空选择
  if (clearBtn) {
    clearBtn.addEventListener('click', () => {
      selectedNames = [];
      updateSelectedCount();
      if (inlinePicker) inlinePicker.style.display = 'none';
      hidePickerOverlay();
    });
  }

  // 点击“选择文件”按钮
  if (fetchBtn) {
    fetchBtn.addEventListener('click', async () => {
      try {
        const resp = await fetch('/list-files');
        const data = await resp.json();
        const items = Array.isArray(data.files) ? data.files : [];
        if (items.length === 0) {
          alert('未在后端data目录发现CSV文件');
          return;
        }
        // 优先使用手机内覆盖层
        if (showPickerOverlay(items)) return;
        // 覆盖层不存在则使用内嵌备选
        renderInlineList(items);
        inlinePicker.style.display = 'block';
      } catch (err) {
        console.error('获取文件列表失败', err);
        alert('获取文件列表失败，请稍后再试');
      }
    });
  }

  // 上传按钮：将选中的文件名映射到后端字段
  const uploadBtn = document.getElementById('upload-btn');
  if (uploadBtn) {
    uploadBtn.addEventListener('click', async () => {
      if (!selectedNames || selectedNames.length === 0) {
        alert('请先选择文件');
        return;
      }
      const mapNameToField = (name) => {
        const lower = name.toLowerCase();
        if (lower.includes('activity')) return 'activity';
        if (lower.includes('glucose')) return 'glucose';
        if (lower.includes('clhls')) return 'clhls';
        return null;
      };
      const payload = {};
      selectedNames.forEach(n => {
        const field = mapNameToField(n);
        if (field) payload[field] = n;
      });
      try {
        const resp = await fetch('/upload-from-list', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });
        const result = await resp.json();
        if (!resp.ok) throw new Error(result.message || '上传失败');
        document.getElementById('upload-success').style.display = 'block';
        // 刷新图表数据
        await refreshChartsData();
      } catch (err) {
        console.error('上传失败', err);
        alert('上传失败，请检查文件名是否匹配 activity/glucose/clhls');
      }
    });
  }
})();

async function checkAlert(personId) {
  try {
    const resp = await fetch(`/alert?person_id=${encodeURIComponent(personId)}`);
    const data = await resp.json();
    if (data && data.alert) {
      showAlertOverlay();
    }
  } catch (err) {
    console.error('预警检查失败', err);
  }
}